<?php
declare (strict_types=1);

namespace upload\engine;

use Qiniu\Auth;
use Qiniu\Http\Error;
use Qiniu\Storage\UploadManager;
use Qiniu\Storage\BucketManager;

/**
 * 七牛云存储引擎
 * Class Qiniu
 * @package upload\engine
 */
class Qiniu extends Base
{
    /**
     * 执行上传
     * @return array|string
     * @throws \Exception
     */
    public function upload(): array|string
    {
        $path = $this->path.'/'.$this->filename;
        // 构建鉴权对象
        $auth = new Auth($this->config['access_key'], $this->config['secret_key']);
        // 要上传的空间
        $token = $auth->uploadToken($this->config['bucket']);
        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        [, $error] = $uploadMgr->putFile($token, $path, $this->file);
        /* @var $error Error */
        if ($error !== null) {
            return $error->message();
        }
        return [
            'path' => $path,
            'url'  => $this->config['domain'].'/'.$path
        ];
    }

    /**
     * 删除文件
     * @param string $filePath
     * @return bool|string
     */
    public function delete(string $filePath): bool|string
    {
        // 构建鉴权对象
        $auth = new Auth($this->config['access_key'], $this->config['secret_key']);
        // 初始化 UploadManager 对象并进行文件的上传
        $bucketMgr = new BucketManager($auth);
        /* @var $error Error */
        [, $error] = $bucketMgr->delete($this->config['bucket'], $filePath);
        if ($error !== null) {
            return $error->message();
        }
        return true;
    }
}
